package Leetcode第一期;

public class 两数相加_2 {

    public static void main(String[] args) {
        ListNode l1=new ListNode(2);
        ListNode l2=new ListNode(4);
        ListNode l3=new ListNode(3);
        l1.next=l2;l2.next=l3;l3.next=null;

        ListNode d1=new ListNode(5);
        ListNode d2=new ListNode(6);
        ListNode d3=new ListNode(4);
        d1.next=d2;d2.next=d3;d3.next=null;
        ListNode node = addTwoNumbers1(l1, d1);
        while (node!=null){
            System.out.print(node.val);
            node=node.next;
        }

    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, curr = dummyHead;
        int carry = 0;
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;  //进位
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if (p != null) p = p.next;
            if (q != null) q = q.next;
        }
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }

    public static ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
        ListNode tempNodes= new ListNode(0);
        ListNode n1=l1,n2=l2,curr=tempNodes;
        int carry=0;

        while (n2!=null || n2!=null){
            int x = (n1 != null) ? n1.val : 0;
            int y = (n2 != null) ? n2.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;  //进位

            curr.next=new ListNode(sum%10);
            curr=curr.next;
            if (n1!=null) n1=n1.next;
            if (n2!=null) n2=n2.next;
        }
        if (carry>0){
            curr.next=new ListNode(carry);
        }
        return tempNodes.next;

    }

}
